package hxy.bytecode.sql;

import java.sql.*;

/**
 * @author eric
 */
public class MyPreparedStatement {
    private final String db_driver = "com.";
    private final String url = "jdbc:microsoft:sqlserver://127.0.preparedStatement0.1:1433;databasename=pubs";

    public MyPreparedStatement() {
    }

    public void query() throws SQLException {
        Connection conn = this.getDBConnection();
        String tableName = "user";
        String strsql = "select * from " + tableName + " where id = ?";
        PreparedStatement pstmt = conn.prepareStatement(strsql);
        // 如果是ORM框架,需要在这里识别参数,一一对应,值与类型都需要考虑
        pstmt.setString(1, "1");
        ResultSet rs = pstmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        System.out.println("columnLabel" +"\tcolumnType" +"\tcolumnName" );
        for (int i = 0; i < columnCount; i++) {
            int j = i + 1;
//            下面应该是从1开始的
            String columnLabel = metaData.getColumnLabel(j);
            int columnType = metaData.getColumnType(j);
            String columnName = metaData.getColumnName(j);
            // 下面是数据类型,参考com.mysql.cj.MysqlType类,继承自sql的接口.


            System.out.println( columnLabel+"\t" + columnType+"\t" + columnName);

        }

        while (rs.next()) {
            // 如果ORM框架,获取值需要一一对应,将对象的属性与数据库的column关联上.那么下面的列应该来自与对象的属性?
            // 万一没有设置对象,那怎么取出值放在结果集里面呢? 从上面ResultSetMetaData类里面就可以直接获取数据库的column列数值
            String fname = rs.getString("name");
            System.out.println("the name is " + fname);
        }
        rs.close();
        pstmt.close();
        conn.close();
    }

    private Connection getConnection() throws SQLException {
// class.
        Connection conn = null;
        try {
            Class.forName(db_driver);
            conn = DriverManager.getConnection(url, "sa", "sa");
        } catch (ClassNotFoundException ex) {
        }
        return conn;
    }

    public Connection getDBConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://cupb.top:3306/eric";
            String user = "eric";
            String password = "newpass";
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    //main
    public static void main(String[] args) throws SQLException {
        MyPreparedStatement jdbctest1 = new MyPreparedStatement();
        jdbctest1.query();
    }
}
